package com.jsoft.aop;

import com.jsoft.annotation.Log;
import com.jsoft.core.RedisTemplate;
import com.jsoft.service.LogService;
import com.jsoft.util.AuthUtil;
import net.sf.jsqlparser.statement.select.Join;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ExecutorService;

/**日志记录
 * @author : handsome Boy
 * @description :
 * @createDate : 2025/3/19 14:09
 */
@Component
@Aspect
public class LogAspect {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogService logService;
    @Autowired
    private ExecutorService executorService;
    //完成操作记录日志
    @AfterReturning("@annotation(log)")
    public void doAfterReturning(JoinPoint joinPoint, Log log){
        HttpServletRequest request =
                ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        logHandler(joinPoint,request,log,null);
    }
    //抛出异常记录日志
    @AfterThrowing(value = "@annotation(log)",throwing = "exception")
    public void doAfterReturning(JoinPoint joinPoint, Log log,Exception exception){
        HttpServletRequest request =
                ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        logHandler(joinPoint,request,log,exception);
    }

    /**
     * 真正去执行日志的操作方法
     * @param joinPoint 切入点,获取method
     * @param request   请求对象,获取url,request_method
     * @param log   日志自定义注解,获取title,businessType
     * @param exception 抛出的异常
     */
    private void logHandler(JoinPoint joinPoint,HttpServletRequest request,Log log,Exception exception){

    //根据现场信息,封装日志对象
    com.jsoft.entity.Log logoper = new com.jsoft.entity.Log();
    //1.oper_id是自动递增,不需要赋值
    //2.title
    logoper.setTitle(log.title());
    //3.businessType
    logoper.setBusinessType(log.businessType());
    //先判断操作是否成功,有没有异常信息
    if(!Objects.isNull(exception)){
        //4.失败的errorMsg
        logoper.setErrormsg(exception.getMessage().length()>100?
                exception.getMessage().substring(0,100):exception.getMessage());
        //5.失败的status
        logoper.setStatus(500);
    }
    else{
        //如果没有异常,说明操作成功
        //成功的errorMsg为空
        //5成功的状态码
        logoper.setStatus(200);
    }
        /**
         *   从redis中读取loginUser
         */
    if(!Objects.isNull(AuthUtil.getLoginUser(redisTemplate))&&
            !Objects.isNull(AuthUtil.getLoginUser(redisTemplate))){
        logoper.setOperName(AuthUtil.getLoginUser(redisTemplate).getUser().getUsername());
    }

        logoper.setOperUrl(request.getRequestURL().toString());

        logoper.setMethod(joinPoint.getSignature().getName());

        logoper.setOpertime(new Date());

        logoper.setRequestMetho((request.getMethod()));

        logoper.setOperIp(request.getRemoteAddr());
        System.out.println(logoper+"11111111111111111111111111111");
        /**
         * 保存并提交日志
         */
        System.out.println("main---------------->"+ Thread.currentThread().getName());
        executorService.execute(()->{
            System.out.println("log---------------->"+ Thread.currentThread().getName());
            logService.insert(logoper);

        });
    }

}
